// pages/selfAssessment/question/subject/subject.js
const api = require('../../../../config/api')
const request = require('../../../../utils/request')
Page({
  /**
   * 页面的初始数据
   */

  data: {
    questionNumber: 0,
    answerList: [],
    isTwoLine: true,
    questionnaireId: '', // 问卷id
    questionType: 1, // 答题类型，1：全部必填题目答完后提交，2：有题目不通过时提交
    questionList: [], // 题目列表
    currentQuestion: {},
    currentOptionCode: '',
    currentOptionName: '',
    answerOptionList: [],
    maxLength: 0, // 题目数量
    key: '',
    pathId: '',
    taskFlowId: '',
    pinyinCode: '', // 拼音码（问卷标识）
    questionKey: '', // 问卷标识
    fromOrigin: 0,// 从活动训练还是普通训练进入
    activityId: '',// 从活动训练训练进入接收活动id
  },
  // 单选
  selectOne: function (e) {
    let { code, name, item } = e.currentTarget.dataset
    let { currentQuestion } = this.data

    if (currentQuestion.type === 5) {
      currentQuestion.subQuestion.map((e) => {
        e.childrenOptionList.map((it) => {
          if (it.optionId === item.optionId) {
            e.selectId = it.optionId
            e.selectCode = it.code
          }
        })
      })
    } else {
      currentQuestion.subQuestion.map((it) => {
        if (it.optionId === item.optionId) {
          it.checked = true
        } else {
          it.checked = false
        }
      })
    }
    this.setData({
      currentOptionCode: code,
      currentOptionName: name,
      currentQuestion: currentQuestion,
    })
  },
  // 多选
  selectRep: function (e) {
    let { currentQuestion } = this.data
    let { index, item } = e.currentTarget.dataset
    if (currentQuestion.type === 6) {
      currentQuestion.subQuestion.map((e) => {
        e.childrenOptionList.map((it) => {
          if (it.optionId === item.optionId) {
            it.checked = !it.checked
          }
        })
      })
    } else {
      currentQuestion.subQuestion[index].checked =
        !currentQuestion.subQuestion[index].checked //点击就赋相反的值
    }

    this.setData({
      currentQuestion: currentQuestion, //将已改变属性的json数组更新
    })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.enableAlertBeforeUnload({
      message: '是否放弃答题',
    })
    const patientInfo = wx.getStorageSync('patientInfo')

    let questionnaireId = ''
    let questionType = 1
    let key = ''
    let pathId = ''
    let taskFlowId = ''
    let pinyinCode = ''
    let questionKey = ''

    if (options.questionnaireId !== 'undefined') {
      questionnaireId = options.questionnaireId
    }
    if (options.questionType !== 'undefined') {
      questionType = options.questionType
    }
    if (options.key) {
      key = options.key
    }
    if (options.pathId) {
      pathId = Number(options.pathId)
    }
    if (options.taskFlowId) {
      taskFlowId = Number(options.taskFlowId)
    }
    if (options.pinyinCode) {
      pinyinCode = options.pinyinCode
    }
    if (options.questionKey) {
      questionKey = options.questionKey
    }
    this.setData({
      patientInfo,
      origin: options?.origin,
      back: options?.back,
      questionnaireId: questionnaireId,
      questionType: questionType,
      key: key,
      pathId: pathId,
      taskFlowId: taskFlowId,
      pinyinCode: pinyinCode,
      questionKey: questionKey,
      fromOrigin: Number(options?.fromOrigin) || 0,
      activityId: options?.activityId || '',
    })

    this.getQuestionList()
  },
  // 判断选项字数，如果最大字数大于10，则使用单列，否则使用双列
  checkFlex() {
    let bol = true
    let { currentQuestion } = this.data
    if (currentQuestion.type === 5 || currentQuestion.type === 6) {
      this.data.currentQuestion?.subQuestion.map((item) => {
        item?.childrenOptionList.map((obj) => {
          if (obj.name.length > 10) {
            bol = false
          }
        })
      })
      this.setData({
        isTwoLine: bol,
      })
    }
  },
  // 题目列表
  getQuestionList: async function () {
    const res = await request.get(api.getQuestionsList, {
      patientId: this.data.patientInfo.id,
      questionnaireId: this.data.questionnaireId,
    })
    if (res.httpStatus === 200) {
      res.data.map((it) => {
        if (it.type === 4) {
          it.mainQuestion = it.mainQuestion.replace(/\(.*?\)/g, '_____')
        }
        it.subQuestion?.map((item) => {
          item.checked = false
          item.selectId = ''

          if (item?.childrenOptionList) {
            item?.childrenOptionList.map((ite) => {
              ite.checked = false
            })
          }
        })
      })

      this.setData({
        questionList: res.data,
        maxLength: res.data.length,
      })
      if (res.data.length > 0) {
        this.setData({
          currentQuestion: res.data[0],
        })
        this.getNavigationBarTitle()
      }
    }
    this.checkFlex()
  },
  getNavigationBarTitle() {
    let type = this.data.currentQuestion.type
    let title = ''
    switch (type) {
      case 1:
        title = '判断题'
        break
      case 2:
        title = '单选题'
        break
      case 3:
        title = '多选题'
        break
      case 4:
        title = '填空题'
        break
      case 5:
        title = '矩阵单选题'
        break
      case 6:
        title = '矩阵多选题'
        break
      default:
        title = '问卷题目'
        break
    }
    wx.setNavigationBarTitle({
      title: title,
    })
  },
  // 下一题
  handleNext() {
    let {
      questionList,
      questionType,
      questionNumber,
      answerOptionList,
      currentQuestion,
      currentOptionName,
      maxLength,
      pinyinCode,
    } = this.data
    let arr = []
    let flag = false

    // 该题目是矩阵题
    if (currentQuestion.type === 5 || currentQuestion.type === 6) {
      // 矩阵单选题
      if (currentQuestion.type === 5) {
        currentQuestion.subQuestion.map((item) => {
          if (!item.selectId) {
            wx.showToast({
              title: '请选择答案!',
              icon: 'none',
            })
            flag = true
            return
          }
        })
        if (flag) {
          wx.showToast({
            title: '请选择答案!',
            icon: 'none',
          })
          return
        }
        currentQuestion.subQuestion.map((it) => {
          if (it.selectCode) {
            arr.push(it.selectCode)
          }
        })
      } else {
        // 矩阵多选题
        currentQuestion.subQuestion.map((e) => {
          let objArr = e.childrenOptionList
          // 矩阵中有一个子题目未选择答案，则提示
          if (objArr.every((target) => target.checked === false)) {
            flag = true
          } else {
            objArr.map((it) => {
              if (it.checked) {
                arr.push(it.code)
              }
            })
          }
        })
        if (flag) {
          wx.showToast({
            title: '请选择答案!',
            icon: 'none',
          })
          return
        }
      }
    } else {
      // 单选、多选、判断题
      currentQuestion.subQuestion.map((item) => {
        if (item.checked) {
          arr.push(item.code)
        }
      })
    }

    let selectOption = arr.join(',')
    if (!selectOption) {
      wx.showToast({
        title: '请选择答案!',
        icon: 'none',
      })
      return
    }

    answerOptionList.push({
      questionId: currentQuestion.id,
      optionValues: selectOption,
    })
    this.setData({
      answerOptionList: answerOptionList,
    })

    if (questionNumber + 1 === maxLength) {
      if (Number(questionType) === 2) {
        this.setData({
          answerOptionList: answerOptionList.splice(
            answerOptionList.length - 1,
            1
          ),
        })
      }
      this.submit()
      return
    }

    // questionType:答题类型，1：全部必填题目答完后提交，2：有题目不通过时提交
    if (Number(questionType) === 1) {
      this.setData({
        currentQuestion: questionList[questionNumber + 1],
        questionNumber: questionNumber + 1,
        isTwoLine: true,
      })
      this.getNavigationBarTitle()
    } else {
      if (currentOptionName === '不能') {
        this.setData({
          answerOptionList: answerOptionList.splice(
            answerOptionList.length - 1,
            1
          ),
        })
        this.submit()
        return
      }
      this.setData({
        currentQuestion: questionList[questionNumber + 1],
        questionNumber: questionNumber + 1,
        isTwoLine: true,
      })
      this.getNavigationBarTitle()
    }
    this.checkFlex()
  },
  // 提交
  submit: async function () {
    const {
      patientInfo,
      questionnaireId,
      answerOptionList,
      maxLength,
      key,
      pathId,
      taskFlowId,
      pinyinCode,
      questionNumber,
      questionList,
      questionType,
      questionKey,
      fromOrigin,
      activityId
    } = this.data
    // let key = key ? 'training' :  Number(questionType) === 1 ? 'zeroToThreeSix' : 'ability'
    let keyword = key ? 'training' : questionKey
    let origin = key ? 3 : 2
    let res = null
    if (pinyinCode === '0-6SETXLXWFYWTYJZXSCB') {
      // 0-6岁问卷
      res = await request.post(api.zeroToSixScreening, {
        origin: origin,
        patientId: Number(patientInfo.id),
        questionnaireId: Number(questionnaireId),
        questionList: answerOptionList,
      })
      if (res.httpStatus === 200) {
        let info = res.data
        // answerState -- 答题是否完成，1/完成（跳转答题记录），2/未完成（继续答题）
        if (info.answerState === 1) {
          wx.navigateTo({
            url: `/pages/selfAssessment/question/result?id=${info.recordId}&isResultList=create`,
          })
        } else {
          this.setData({
            questionList: [...questionList, ...info.questionList],
            currentQuestion: info.questionList[0],
            questionNumber: questionNumber + 1,
            maxLength: maxLength + 1,
          })
          this.getNavigationBarTitle()
        }
      }
    } else {
      // 其他问卷
      res = await request.post(api.questionCalculation, {
        key: keyword,
        origin: origin,
        patientId: Number(patientInfo.id),
        questionnaireId: Number(questionnaireId),
        questionList: answerOptionList,
        taskFlowId,
        pathId,
      })
      if (res.httpStatus === 200) {
        if (key === 'training') {
          wx.redirectTo({
            url: `/pages/selfAssessment/question/result?id=${res.data}&isTraining=isTraining&pathId=${pathId}&fromOrigin=${fromOrigin}&activityId=${activityId}`,
          })
        } else {
          wx.navigateTo({
            url: `/pages/selfAssessment/question/result?id=${res.data}&isResultList=create&fromOrigin=${fromOrigin}&activityId=${activityId}`,
          })
        }
      }
    }
  },
  // 点击查看图片大图
  handlePreview(val) {
    let url = val.currentTarget.dataset.url
    let arr = []
    arr.push(url)
    wx.previewImage({
      current: url, //当前图片地址
      urls: arr, //所有要预览的图片的地址集合 数组形式
      success: function (res) {},
      fail: function (res) {},
      complete: function (res) {},
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {},

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    wx.disableAlertBeforeUnload()
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
})
